package org.dromara.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;
import org.dromara.system.domain.bo.EmailAccountBo;
import org.dromara.system.domain.vo.EmailAccountVo;
import org.dromara.system.domain.EmailAccount;
import org.dromara.system.mapper.EmailAccountMapper;
import org.dromara.system.service.IEmailAccountService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 邮箱账号Service业务层处理
 *
 * @author Gavino
 * @date 2024-11-18
 */
@RequiredArgsConstructor
@Service
public class EmailAccountServiceImpl implements IEmailAccountService {

    private final EmailAccountMapper baseMapper;

    /**
     * 查询邮箱账号列表
     *
     * @param accountIds 邮箱账号Id
     * @param createId   代理人ID
     * @param type       账号类型
     * @return 邮箱账号集合
     */
    @Override
    public List<EmailAccount> selectAccountList(List<Long> accountIds, Long createId, Integer type) {

        LambdaUpdateWrapper<EmailAccount> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.eq(EmailAccount::getStatus, 0);
        queryWrapper.in(accountIds != null && !accountIds.isEmpty(), EmailAccount::getId, accountIds);
        queryWrapper.eq(createId != null, EmailAccount::getCreateId, createId);
        queryWrapper.eq(type != null, EmailAccount::getType, type);

        return baseMapper.selectList(queryWrapper);
    }

    /**
     * 更新代理的邮箱账号类型
     *
     * @param createId   代理ID
     * @param accountIds 账号Ids
     * @param oldType    之前类型
     * @param type       更新为什么类型
     */
    @Override
    public void updateAgentAccountAType(Long createId, List<Long> accountIds, Integer oldType, Integer type) {
        LambdaUpdateWrapper<EmailAccount> update = new LambdaUpdateWrapper<>();
        update.eq(EmailAccount::getCreateId, createId);
        update.eq(oldType != null, EmailAccount::getType, oldType);
        update.in(accountIds != null && !accountIds.isEmpty(), EmailAccount::getId, accountIds);

        update.set(EmailAccount::getType, type);
        baseMapper.update(update);
    }

    /**
     * 查询代理的邮箱账号列表
     *
     * @param agentId 代理ID
     * @param type    账号类型
     * @param status  状态
     * @return 邮箱账号集合
     */
    @Override
    public List<EmailAccount> selectAgentAccountList(Long agentId, Integer type, Integer status) {
        LambdaQueryWrapper<EmailAccount> query = new LambdaQueryWrapper<>();
        query.eq(EmailAccount::getCreateId, agentId);
        query.eq(type != null, EmailAccount::getType, type);
        query.eq(status != null, EmailAccount::getStatus, status);
        query.eq(EmailAccount::getIsDelete, 0);
        return baseMapper.selectList(query);
    }

    /**
     * 查询邮箱账号
     *
     * @param id 主键
     * @return 邮箱账号
     */
    @Override
    public EmailAccountVo queryById(Long id) {
        return baseMapper.selectVoById(id);
    }

    /**
     * 分页查询邮箱账号列表
     *
     * @param bo        查询条件
     * @param pageQuery 分页参数
     * @return 邮箱账号分页列表
     */
    @Override
    public TableDataInfo<EmailAccountVo> queryPageList(EmailAccountBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<EmailAccount> lqw = buildQueryWrapper(bo);
        Page<EmailAccountVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的邮箱账号列表
     *
     * @param bo 查询条件
     * @return 邮箱账号列表
     */
    @Override
    public List<EmailAccountVo> queryList(EmailAccountBo bo) {
        LambdaQueryWrapper<EmailAccount> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<EmailAccount> buildQueryWrapper(EmailAccountBo bo) {
        Map<String, Object> params = bo.getParams();
        if (LoginHelper.isService()) {
            bo.setCreateId(LoginHelper.getLoginUser().getAgentId());
            bo.setIsDelete(0);
        }
        else if (!LoginHelper.isSuperAdmin()) {
            bo.setCreateId(LoginHelper.getUserId());
            bo.setIsDelete(0);
        }

        LambdaQueryWrapper<EmailAccount> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getAccount()), EmailAccount::getAccount, bo.getAccount());
        lqw.eq(StringUtils.isNotBlank(bo.getPassword()), EmailAccount::getPassword, bo.getPassword());
        lqw.eq(StringUtils.isNotBlank(bo.getAgreement()), EmailAccount::getAgreement, bo.getAgreement());
        lqw.eq(StringUtils.isNotBlank(bo.getServer()), EmailAccount::getServer, bo.getServer());
        lqw.eq(StringUtils.isNotBlank(bo.getPort()), EmailAccount::getPort, bo.getPort());
        lqw.eq(bo.getStatus() != null, EmailAccount::getStatus, bo.getStatus());
        lqw.eq(bo.getType() != null, EmailAccount::getType, bo.getType());
        lqw.eq(bo.getEnableSsl() != null, EmailAccount::getEnableSsl, bo.getEnableSsl());
        lqw.eq(bo.getIsDelete() != null, EmailAccount::getIsDelete, bo.getIsDelete());
        lqw.eq(bo.getCreateId() != null, EmailAccount::getCreateId, bo.getCreateId());
        lqw.like(StringUtils.isNotBlank(bo.getCreateName()), EmailAccount::getCreateName, bo.getCreateName());
        lqw.eq(bo.getUpdateId() != null, EmailAccount::getUpdateId, bo.getUpdateId());
        lqw.like(StringUtils.isNotBlank(bo.getUpdateName()), EmailAccount::getUpdateName, bo.getUpdateName());
        lqw.like(StringUtils.isNotBlank(bo.getRemark()), EmailAccount::getRemark, bo.getRemark());
        return lqw;
    }

    /**
     * 新增邮箱账号
     *
     * @param bo 邮箱账号
     * @return 是否新增成功
     */
    @Override
    public Boolean insertByBo(EmailAccountBo bo) {
        EmailAccount add = MapstructUtils.convert(bo, EmailAccount.class);
        validEntityBeforeSave(add);
        add.setIsDelete(0);
        add.setStatus(0);
        add.setType(0);
        if (LoginHelper.isService()) {
            add.setCreateId(LoginHelper.getLoginUser().getAgentId());
            add.setCreateName(LoginHelper.getLoginUser().getAgentName());
        } else {
            add.setCreateId(LoginHelper.getUserId());
            add.setCreateName(LoginHelper.getUsername());
        }
        add.setCreateTime(DateUtils.getNowDate());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改邮箱账号
     *
     * @param bo 邮箱账号
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(EmailAccountBo bo) {
        EmailAccount update = MapstructUtils.convert(bo, EmailAccount.class);
        validEntityBeforeSave(update);
        update.setUpdateId(LoginHelper.getUserId());
        update.setUpdateName(LoginHelper.getUsername());
        update.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(EmailAccount entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 校验并批量删除邮箱账号信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        LambdaQueryWrapper<EmailAccount> query = new LambdaQueryWrapper<>();
        query.in(EmailAccount::getId, ids);
        if (LoginHelper.isAgent()) {
            query.eq(EmailAccount::getCreateId, LoginHelper.getUserId());
        }
        return baseMapper.delete(query) > 0;
    }
}
